<script setup lang="ts">
import type { RuleObject } from 'ant-design-vue/es/form';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';
import { cloneDeep } from '@vben/utils';

import {
  Form,
  FormItem,
  Input,
  Textarea,
  InputNumber,
  TimePicker,
} from 'ant-design-vue';
import { useBeforeCloseDiff } from '#/utils/popup';
import type { FollowUpConfigForm, PlanConfigVO } from '#/api/healthPlan/config/planConfig/model';
import { planConfigInfo, planConfigUpdate } from '#/api/healthPlan/config/planConfig';


const emit = defineEmits<{ reload: [] }>();

const isUpdate = ref(false);
const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
/**
 * 定义默认值 用于reset
 */
const defaultValues: FollowUpConfigForm = {
  id: undefined,
  reminderName: undefined,
  reminderContent: undefined,
  reminderTime: undefined,
  deptName: undefined,
  triggerType: 'RELATIVE_TO_CYCLE',
  daysAfter: undefined
};

/**
 * 表单数据ref
 */
const formData = ref(defaultValues);

const cycleData = ref<string[]>([])

const taskData = ref<PlanConfigVO | null>(null)

type AntdFormRules<T> = Partial<Record<keyof T, RuleObject[]>> & {
  [key: string]: RuleObject[];
};
/**
 * 表单校验规则
 */
const formRules = ref<AntdFormRules<FollowUpConfigForm>>({
  reminderName: [{ required: true, message: $t('ui.formRules.required') }],
  reminderContent: [{ required: true, message: $t('ui.formRules.required') }],
  deptName: [{ required: true, message: $t('ui.formRules.required') }],
  reminderTime: [{ required: true, message: $t('ui.formRules.required') }],
  triggerType: [{ required: true, message: $t('ui.formRules.required') }],
  daysAfter: [{ required: true, message: $t('ui.formRules.required') }],
});

/**
 * useForm解构出表单方法
 */
const { validate, validateInfos, resetFields } = Form.useForm(
  formData,
  formRules,
);

function customFormValueGetter() {
  return JSON.stringify(formData.value);
}

const { onBeforeClose, markInitialized, resetInitialized } = useBeforeCloseDiff(
  {
    initializedGetter: customFormValueGetter,
    currentGetter: customFormValueGetter,
  },
);

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[600px]',
  fullscreenButton: true,
  closeOnClickModal: false,
  onBeforeClose,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    const { id, cycleData } = modalApi.getData();
    taskData.value = await planConfigInfo(id);
    cycleData.value = cycleData
    isUpdate.value = !!id;
    if (isUpdate.value && id && taskData) {
      const taskConfig = taskData.value.taskConfig || {}
      const triggerConfig = taskData.value.triggerConfig || {}
      const record = { ...defaultValues, id, ...taskConfig, ...triggerConfig }
      formData.value = record;
    }
    await markInitialized();
    modalApi.modalLoading(false);
  },
});

async function handleConfirm() {
  try {
    modalApi.modalLoading(true);
    await validate();
    // 可能会做数据处理 使用cloneDeep深拷贝
    const data = cloneDeep(formData.value);
    const { deptName, triggerType, daysAfter, reminderContent, reminderName, reminderTime } = data
    // 重新组装数据
    const makeData = {
      triggerType,
      // 任务配置
      taskConfig: {
        deptName,
        reminderContent,
        reminderName,
        reminderTime,
      },
      // 触发时间配置
      triggerConfig: {
        daysAfter
      },
    }
    const submitData = {
      ...taskData.value, ...makeData
    }
    await planConfigUpdate(submitData);
    resetInitialized();
    emit('reload');
    modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleClosed() {
  formData.value = defaultValues;
  resetFields();
  resetInitialized()
}
</script>

<template>
  <BasicModal :title="title">
    <Form>
      <FormItem label="提醒标题" v-bind="validateInfos.reminderName">
        <Input :placeholder="$t('ui.formRules.required')" v-model:value="formData.reminderName" />
      </FormItem>
      <FormItem label="提醒内容" v-bind="validateInfos.reminderContent">
        <Textarea :placeholder="$t('ui.formRules.required')" :rows="4" v-model:value="formData.reminderContent" />
      </FormItem>
      <FormItem label="就诊科室" v-bind="validateInfos.deptName">
        <Input :placeholder="$t('ui.formRules.required')" v-model:value="formData.deptName" />
      </FormItem>
      <FormItem label="提醒日期" v-bind="validateInfos.daysAfter">
        <InputNumber :placeholder="$t('ui.formRules.required')" v-model:value="formData.daysAfter" addon-before="周期内第"
          addon-after="天" :min="1"></InputNumber>
      </FormItem>
      <FormItem label="提醒时间" v-bind="validateInfos.reminderTime">
        <TimePicker class="w-full" v-model:value="formData.reminderTime" format="HH:mm:ss" value-format="HH:mm:ss"
          :placeholder="$t('ui.formRules.required')" />
      </FormItem>
    </Form>
  </BasicModal>
</template>
